<?php
namespace app\hotback\controller;
use think\Db;
class Proxy extends Base
{
	public function _initialize()
	{
		// 调用父类前置方法
		parent::_initialize();

		// 登录校验
		$this->IsLogin();
	}

	/**
	 * 服务列表
	 */
	public function index()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		if(request()->isPost())
		{
			$params = input();
			if(!empty($params['page']) && !empty($params['limit']))
			{
				$map = [
					'p.is_delete_time' => 0,
					'p.type'=>1
				];
				if(!empty($params['company_name']))
				{
					$map['p.company_name'] = ['like','%'.$params['company_name'].'%'];
				}


				/*
                $count = Db::name('proxy')->where($map)->count();
				$list_data = Db::name('proxy')->where($map)->order('proxy_id desc')->limit(($params['page']-1)*$params['limit'],$params['limit'])->select();
                */

                $count = Db::table('jx_proxy')
                    ->alias('p')
                    ->join('area a','p.sheng = a.id')
                    ->join('area s','p.shi = s.id')
                    ->order('p.proxy_id desc')
                    ->field('p.proxy_id,p.user_name,p.company_name,p.add_time,p.qu as qustr,a.name as sheng,s.name as shi')
                    ->where($map)
                    ->count();

                $list_data = Db::table('jx_proxy')
                    ->alias('p')
                    ->join('area a','p.sheng = a.id')
                    ->join('area s','p.shi = s.id')
                    ->order('p.proxy_id desc')
                    ->limit(($params['page']-1)*$params['limit'],$params['limit'])
                    ->field('p.proxy_id,p.type,p.commission,p.user_name,p.company_name,p.add_time,p.qu as qustr,a.name as sheng,s.name as shi')
                    ->where($map)
                    ->select();

                if(!empty($list_data))
				{
					//遍历处理
					foreach($list_data as $key => $value)
					{
						//编辑url
						$list_data[$key]['save_url'] = url('proxy/saveinfo', ['proxy_id' => $value['proxy_id'],'type'=>1]);
                        $list_data[$key]['add_time'] = date("Y-m-d H:i:s",$value['add_time']);

                        switch ($value['type']) {
                            case 1:
                                $list_data[$key]['typename'] = '分公司';
                                 break;
                            case 2:
                                $list_data[$key]['typename'] = '加盟商';
                                break;
                            default:
                                $list_data[$key]['typename'] = '无';
                        }

                        $qustr = $value['qustr'];

                        $qulists = Db::name('Area')->where('id','in',$qustr)->column('name');

                        if(!empty($qulists)) {
                            $qu_str = '';
                            foreach ($qulists AS $k=>$v) {
                                $qu_str.=$v.",";
                            }
                            $qu_str = substr($qu_str,0,strlen($qu_str)-1);
                            $list_data[$key]['qu'] = $qu_str;
                        }

					}
					$result['code'] = 0;
	        		$result['msg'] = "请求成功";
	        		$result['data'] = $list_data;
	        		$result['count'] = $count;
				}else
				{
					$result['code'] = -1;
	        		$result['msg'] = "暂无数据";
				}
			}
			echo json_encode($result);
		}else
		{
		    $day=db::name('xunh')->where('proxy_id',0)->value('day');
		    
		    $this->assign('day',$day);
		    
			return $this->fetch();
		}
	}
	
	
	public function index2()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		if(request()->isPost())
		{
			$params = input();
			if(!empty($params['page']) && !empty($params['limit']))
			{
				$map = [
					'p.is_delete_time' => 0,
					'p.type'=>2
				];
				if(!empty($params['company_name']))
				{
					$map['p.company_name'] = ['like','%'.$params['company_name'].'%'];
				}


				/*
                $count = Db::name('proxy')->where($map)->count();
				$list_data = Db::name('proxy')->where($map)->order('proxy_id desc')->limit(($params['page']-1)*$params['limit'],$params['limit'])->select();
                */

                $count = Db::table('jx_proxy')
                    ->alias('p')
                    ->join('area a','p.sheng = a.id')
                    ->join('area s','p.shi = s.id')
                    ->order('p.proxy_id desc')
                    ->field('p.proxy_id,p.user_name,p.company_name,p.add_time,p.qu as qustr,a.name as sheng,s.name as shi')
                    ->where($map)
                    ->count();

                $list_data = Db::table('jx_proxy')
                    ->alias('p')
                    ->join('area a','p.sheng = a.id')
                    ->join('area s','p.shi = s.id')
                    ->order('p.proxy_id desc')
                    ->limit(($params['page']-1)*$params['limit'],$params['limit'])
                    ->field('p.proxy_id,p.type,p.commission,p.user_name,p.company_name,p.add_time,p.qu as qustr,a.name as sheng,s.name as shi')
                    ->where($map)
                    ->select();

                if(!empty($list_data))
				{
					//遍历处理
					foreach($list_data as $key => $value)
					{
						//编辑url
						$list_data[$key]['save_url'] = url('proxy/saveinfo', ['proxy_id' => $value['proxy_id'],'type'=>2]);
                        $list_data[$key]['add_time'] = date("Y-m-d H:i:s",$value['add_time']);

                        switch ($value['type']) {
                            case 1:
                                $list_data[$key]['typename'] = '分公司';
                                 break;
                            case 2:
                                $list_data[$key]['typename'] = '加盟商';
                                break;
                            default:
                                $list_data[$key]['typename'] = '无';
                        }

                        $qustr = $value['qustr'];

                        $qulists = Db::name('Area')->where('id','in',$qustr)->column('name');

                        if(!empty($qulists)) {
                            $qu_str = '';
                            foreach ($qulists AS $k=>$v) {
                                $qu_str.=$v.",";
                            }
                            $qu_str = substr($qu_str,0,strlen($qu_str)-1);
                            $list_data[$key]['qu'] = $qu_str;
                        }

					}
					$result['code'] = 0;
	        		$result['msg'] = "请求成功";
	        		$result['data'] = $list_data;
	        		$result['count'] = $count;
				}else
				{
					$result['code'] = -1;
	        		$result['msg'] = "暂无数据";
				}
			}
			echo json_encode($result);
		}else
		{
		    $day=db::name('xunh')->where('proxy_id',0)->value('day');
		    
		    $this->assign('day',$day);
		    
			return $this->fetch('');
		}
	}

	/**
	 * 服添添加/修改 页面
	 */
	public function saveinfo()
	{
		// 参数
		$params = input();
		$info = [];
        $proxy_id = 0;
        $sheng = [];
        $shi = [];
        $qu = [];
        $html = '';

        $shi_arr = [];
        $qu_arr=[];

		if(!empty($params['proxy_id']))
		{
            //查询
			$info = Db::name('Proxy')->where(['proxy_id' => $params['proxy_id']])->find();
            $proxy_id = $params['proxy_id'];

            if($info['sheng']) {
                $shi_arr =Db::name('Area')->where(['pid' => $info['sheng'],'is_enable'=>'1'])->select();
            }

            if($info['shi']) {
                $qu_arr =Db::name('Area')->where(['pid' => $info['shi'],'is_enable'=>'1'])->select();
                $qu = [];
                if($proxy_id) {
                    $proxy_info = Db::name('Proxy')->where("proxy_id = '$proxy_id' ")->find();
                    if(!empty($proxy_info['qu'])) {
                        $qu = explode(',',$proxy_info['qu']);
                    }
                }

                if(!empty($qu_arr)) {
                    foreach ($qu_arr AS $k=>$v) {
                        $id = $v['id'];
                        $res = Db::name('Proxy')->where("FIND_IN_SET($id,qu) AND proxy_id != '$proxy_id' ")->find();
                        if($res) {
                            $html  .='<input type="checkbox" name="qu['.$v['id'].']" lay-skin="primary" title="'.$v['name'].'"  disabled=""  >';
                        }else {
                            if(in_array($v['id'],$qu)) {
                                $html  .='<input type="checkbox" name="qu['.$v['id'].']" lay-skin="primary" title="'.$v['name'].'"  checked=""  >';
                            }else {
                                $html  .='<input type="checkbox" name="qu['.$v['id'].']" lay-skin="primary" title="'.$v['name'].'"   >';
                            }
                        }
                    }
                }
            }

		}

        $area = [];
        $area = Db::name('Area')->where(['pid' => '0','is_enable'=>'1'])->select();
        $this->assign('area',$area);

		$this->assign('info',$info);
		//编辑器文件存放地址
		$this->assign('editor_path_type', 'service');
        $this->assign('proxy_id',$proxy_id);

        $this->assign('shi_arr',$shi_arr);
        $this->assign('qu_list',$html);

		return $this->fetch();
	}

    public function area() {
        $params = input();
        $id = $params['id'];
        $area = Db::name('Area')->where(['pid' => $id,'is_enable'=>'1'])->select();

        $result = array();
        if($area) {
            $result['code'] = 1;
            $result['msg'] = "请求成功";
            $result['data'] = $area;

        }else {
            $result['code'] = 0;
            $result['msg'] = "请求失败";
        }

        return json($result);
    }

    public function area_qu() {
        $params = input();
        $id = $params['id'];
        $proxy_id = isset($params['proxy_id']) ?  $params['proxy_id'] : 0;

        if($id == '0') {
            $result['code'] = 0;
            $result['msg'] = "请选择市";
            return json($result);
        }

        $area = Db::name('Area')->where(['pid' => $id,'is_enable'=>'1'])->select();
        $html = '';


        $qu = [];
        if($proxy_id) {
            $proxy_info = Db::name('Proxy')->where("proxy_id = '$proxy_id' ")->find();
            if(!empty($proxy_info['qu'])) {
                $qu = explode(',',$proxy_info['qu']);
            }
        }

        foreach ($area AS $k=>$v) {
            $id = $v['id'];
            $res = Db::name('Proxy')->where("FIND_IN_SET($id,qu) AND proxy_id != '$proxy_id' ")->find();
            if($res) {
                $html  .='<input type="checkbox" name="qu['.$v['id'].']" lay-skin="primary" title="'.$v['name'].'"  disabled=""  >';
            }else {
                if(in_array($v['id'],$qu)) {
                    $html  .='<input type="checkbox" name="qu['.$v['id'].']" lay-skin="primary" title="'.$v['name'].'"  checked=""  >';
                }else {
                    $html  .='<input type="checkbox" name="qu['.$v['id'].']" lay-skin="primary" title="'.$v['name'].'"   >';
                }
            }
        }

        $result = array();
        if($area) {
            $result['code'] = 1;
            $result['msg'] = "请求成功";
            $result['data'] = $html;

        }else {
            $result['code'] = 0;
            $result['msg'] = "请求失败";
        }

        return json($result);
    }


	/**
	 * 服务添加/修改
	 */
	public function save()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		if(request()->isPost())
		{
			$params = input();

			$validate = $this->validate(
				$params,
				[
					'user_name' => 'require|unique:proxy,is_delete_time=0&user_name='.$params['user_name'],
					'company_name' => 'require',
                    'sheng'=>'require',
                    'shi'=>'require',
                    'qu'=>'require',
                    'type'=>'require',
				],
				[
					'user_name.require' => '请输入用户名',
					'user_name.unique' => '用户名已存在',
					'company_name.require' => '请填写机构名称',
                    'sheng'=>'请选择省',
                    'shi'=>'请选择市',
                    'qu'=>'请选择区',
                    'type'=>'请选类型',
				]
			);
			if(true !== $validate)
			{
				echo json_encode(['code' => -1, 'msg' => $validate]);
				exit();
			}

			//基础数据
			$data = [
				'user_name' => $params['user_name'],
				'company_name' => $params['company_name'],
                'sheng' => $params['sheng'],
                'shi' => $params['shi'],
                'type' => $params['type'],
                'commission' => $params['commission'],
                'day' => $params['day'],
                'is_xian' => isset($params['is_xian']) ? $params['is_xian'] : 0,
			];

            $qus = $params['qu'];

            if(!empty($qus)) {
                $qustr = '';
                foreach ($qus AS $key=>$val) {
                    $qustr .= $key.",";
                }
                $qu = substr($qustr,0,strlen($qustr)-1);
                $data['qu'] = $qu;
            }


            if(!empty($params['password'])) {
                if($params['password'] != $params['repassword'])  {
                    $result['code'] = -1;
                    $result['msg'] = "两次密码不一致";
                    echo json_encode($result);
                    exit;
                }else {
                    $code  = GetRandomStr(6);
                    $newpassword = CheckMd5($params['password'],$code);
                    $data['code'] = $code;
                    $data['password'] = $newpassword;
                }
            }


			// 添加/编辑
			if(empty($params['proxy_id']))
			{
                $user_name = $params['user_name'];
                $proxy_info = Db::name('Proxy')->where("user_name = '$user_name'")->find();
                if($proxy_info) {
                    $result['code'] = -1;
                    $result['msg'] = "用户名已存在";
                    echo json_encode($result);
                    exit;
                }

                if($params['password'] == '') {
                    $result['code'] = -1;
                    $result['msg'] = "请输入密码";
                    echo json_encode($result);
                    exit;
                }


                $data['add_time'] = time();
        		$data['upd_time'] = time();
        		$proxy_id = Db::name('proxy')->insertGetId($data);
			}else
			{
                $proxy_id = $params['proxy_id'];
                $user_name = $params['user_name'];
                $proxy_info = Db::name('Proxy')->where("user_name = '$user_name' and proxy_id != '$proxy_id'")->find();
                if($proxy_info) {
                    $result['code'] = -1;
                    $result['msg'] = "用户名已存在";
                    echo json_encode($result);
                    exit;
                }

                $data['upd_time'] = time();
				if(Db::name('proxy')->where(['proxy_id'=>intval($params['proxy_id'])])->update($data))
				{
                    $proxy_id = $params['proxy_id'];
				}
			}
			//是否成功
			if(isset($proxy_id) && $proxy_id > 0)
			{
				$result['code'] = 0;
				$result['msg'] = "操作成功";
			}else
			{
				$result['code'] = -1;
				$result['msg'] = "操作失败";
			}
		}
		echo json_encode($result);
	}

	/**
	 * 服务删除
	 */
	public function delete()
	{
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		if(request()->isPost())
		{
			$params = input();
			$data = [
				'is_delete_time' => time(),
				'upd_time' => time()
			];
			if(Db::name('proxy')->where(['proxy_id' => intval($params['proxy_id'])])->update($data))
			{
				$result['code'] = 0;
				$result['msg'] = "删除成功";
			}else
			{
				$result['code'] = -1;
				$result['msg'] = "删除失败";
			}
		}
		echo json_encode($result);
	}
}